package com.cerosoft.utils;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.cerosoft.api.http.models.BaseModel;

public abstract class AbstractCacheAdapter<E extends BaseModel> extends
		BaseAdapter {

	public AbstractCacheAdapter(Context c) {
		mContext = c;
		inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	private Context mContext;
	private LayoutInflater inflater;
	List<Integer> lstPosition = new ArrayList<Integer>();
	List<View> lstView = new ArrayList<View>();
	private List<E> list = new ArrayList<E>();

	private void resetAll() {
		lstPosition.clear();
		lstView.clear();
		list.clear();
	}

	@Override
	public void notifyDataSetChanged() {
		resetAll();
		super.notifyDataSetChanged();
	}

	private int MAX = 50;

	public List<E> getList() {
		return list;
	}

	public void setMAX(int mAX) {
		MAX = mAX;
	}

	public int getMAX() {
		return MAX;
	}

	public LayoutInflater getInflater() {
		return inflater;
	}

	protected abstract View initConvertView(final int position);

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (lstPosition.contains(position) == false) {
			if (lstPosition.size() >= MAX)// 这里设置缓存的Item数量
			{
				lstPosition.remove(0);// 删除第一项
				lstView.remove(0);// 删除第一项
			}
			convertView = initConvertView(position);

			lstPosition.add(position);// 添加最新项
			lstView.add(convertView);// 添加最新项
		} else {
			convertView = lstView.get(lstPosition.indexOf(position));
		}

		return convertView;
	}

}
